﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ValidationUnity
{

    public class StringRuleAttribute : AttributeBase
    {
        public StringRuleAttribute(int minLength, int maxLength, string errorMessage = null)
        {
            MinLength = minLength;
            MaxLength = maxLength;
            if (string.IsNullOrEmpty(errorMessage))
            {
                var sb = new StringBuilder(1024);
                sb.Append("The length of character should between ");
                sb.Append(minLength);
                sb.Append(" and ");
                sb.Append(maxLength);
                ErrorMessage = sb.ToString();
            }
            else
            {
                ErrorMessage = errorMessage;
            }
        }
        private int MinLength { get; }
        private int MaxLength { get; }

        public override bool IsValid(object obj)
        {
            if (obj == null)
                return false;
            var length = obj.ToString().Trim().Length;
            if (length > MaxLength || length < MinLength)
                return false;
            return true;
        }
    }
}
